﻿namespace CountTxtFiles
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //定义起始时间dt1
            DateTime dt1 = DateTime.Now;
            //定义路径名为str
            string str1 = @"C:\";
            string str2 = @"D:\";
            //定义存入所有目录的链表
            List<string> dirList = new List<string>();
            //定义存入所有text文件名的链表
            List<string> fileList = new List<string>();
            CountAllTxtFiles(str1, dirList,fileList);
            CountAllTxtFiles(str2 ,dirList,fileList);
            //输出查找的根目录
            Console.WriteLine($"查找的根目录为：{str1}和{str2}\n");
            Console.WriteLine();

            //输出该目录下的所有txt文件名
            /*Console.WriteLine("该目录下的所有txt文件为：");
            foreach (string file in fileList)
            {
                Console.WriteLine(file);
            }
            Console.WriteLine();*/

            Console.WriteLine($"该目录下所有txt文件数为：{fileList.Count}个");
            DateTime dt2 = DateTime.Now;
            TimeSpan ts = dt2 - dt1;
            Console.WriteLine($"查找这些文件一共花了{ts.Seconds}秒");
        }

        /// <summary>
        /// 写一个递归函数用来递归遍历给定目录下所有目录以及子目录
        /// </summary>
        /// <param name="path">传入根目录路径</param>
        /// <param name="list">传入用于存储子目录名称的链表</param>
        /// <param name="list2">传入用于存储txt文件名称的链表</param>
        public static void CountAllTxtFiles(string path, List<string> list1, List<string> list2)
        {
            //list1用来存入文件路径
            List<string> dirList = list1;
            //list2用来存入txt文件名
            List<string> fileList = list2;
            //定义变量allDir是获取当前路径中的所有文件夹目录
            var allDir = Directory.GetDirectories(path);
            //定义变量allTxtFiles是获取当前路径中所有的txt文件
            var allTxtFiles = Directory.EnumerateFiles(path, "*.txt");
            //定义链表subdirectories存入当前路径中的所有文件夹目录
            List<string> subdirectories = new List<string>();
            //遍历

                foreach (var file in allDir)
                {
                    try
                    {
                        subdirectories.Add(file);
                        dirList.Add(file);
                    }
                    catch { }
                    
                    }
                foreach (var file in allTxtFiles)
                {
                    fileList.Add(file);
                }
                foreach (var file in subdirectories)
                {
                    try
                    {
                        CountAllTxtFiles(file, list1, list2);
                    }
                    catch { }
                
                    
                }



        }

       

    }
}